/**
 * 
 */
package com.foreveross.bsl.mam.app.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.UUID;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.bsl.auth.constant.Constant;
import com.foreveross.bsl.common.utils.bean.Constants;
import com.foreveross.bsl.common.utils.context.ContextThead;
import com.foreveross.bsl.file.storage.FileStorage;
import com.foreveross.bsl.file.storage.FileStorageFactory;
import com.foreveross.bsl.mam.app.application.AppMainApplication;
import com.foreveross.bsl.mam.app.application.AppPackageMetaInfoApplication;
import com.foreveross.bsl.mam.app.application.AppSecretApplication;
import com.foreveross.bsl.mam.app.application.AppVersionApplication;
import com.foreveross.bsl.mam.app.application.DefindApplication;
import com.foreveross.bsl.mam.app.application.vo.AppMainVo;
import com.foreveross.bsl.mam.app.application.vo.AppSecretVo;
import com.foreveross.bsl.mam.app.application.vo.AppVersionVo;
import com.foreveross.bsl.mam.app.application.vo.DefindVo;
import com.foreveross.bsl.mam.app.application.vo.PackageTaskVo;
import com.foreveross.bsl.mam.model.application.AttachmentApplication;
import com.foreveross.bsl.mam.model.application.vo.AttachmentVO;
import com.foreveross.bsl.pkg.application.AppPackageApplication;
import com.foreveross.bsl.pkg.application.vo.PackageRequestVo;
import com.foreveross.bsl.system.application.ApplicationRegisterApplication;
import com.foreveross.bsl.system.application.vo.ApplicationRegisterVO;
import com.taobao.common.tfs.packet.FileInfo;

/**
 * [打包服务控制]<BR>
 * [功能详细描述]
 * 
 * @author 冯伟立
 * @version [bsl-web, 2013-7-3]
 */
@Controller
@RequestMapping("/mam/pkg")
public class AppPackageController {

	private Log log = LogFactory.getLog(AppPackageController.class);
	@Autowired
	private AppPackageApplication appPackageApplication;

	@Inject
	private AppVersionApplication appVersionApplication;
	@Inject
	private AppMainApplication appMainApplication;
	@Inject
	private ApplicationRegisterApplication applicationRegisterApplication;

	@Inject
	private AttachmentApplication attachmentApplication;

	private ResourceBundle rb = ResourceBundle.getBundle("config");

	@Inject
	private AppPackageMetaInfoApplication appPkgMetaInfoApplication;

	@Inject
	private DefindApplication defindApplication;

	@Inject
	private AppSecretApplication appSecretApplication;

	/**
	 * [异步请求打包操作] 上传安装包
	 * 
	 * @param args
	 *            2013-7-3 上午11:52:19
	 */
	@ResponseBody
	@RequestMapping("/bundle/{versionId}")
	public Map<String, Object> bundle(
			@PathVariable("versionId") String versionId,
			@RequestParam("bundle") String bundle, HttpServletRequest request) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			AppVersionVo appversion = appVersionApplication
					.getEntity(versionId);
			// 生成plist
			if ("ios".equals(appversion.getPlatformid())) {
				String plistId = this.getPlistTemplate(
						appversion.getApplicationid(), bundle, request);
				appversion.setPlist(plistId);
			}
			if (StringUtils.isNotEmpty(bundle)) {
				appversion.setStatus(3);// 已激活
				appversion.setBundle(bundle);
			} else {
				appversion.setStatus(0);
			}
			appversion.setModified_time(new Date());
			appVersionApplication.updateEntity(appversion.getId(), appversion);
			result.put("result", "success");
			result.put("platformid", appversion.getPlatformid());
		} catch (Exception e) {
			log.error("[bundle]", e);
			result.clear();
			result.put("result", "error");
		}
		log.info("[bundle]" + result.toString());
		return result;
	}

	/**
	 * 请求打包服务逻辑处理接口 [功能详细描述]
	 * 
	 * @param args
	 *            2013-7-3 上午11:52:19
	 */
	@ResponseBody
	@RequestMapping("/package")
	public Map<String, Object> packageAdd(
			@RequestBody Map<String, String> mapParams,
			HttpServletRequest request) {
		log.info("[packageAdd]" + mapParams.toString());
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Date date = new Date();
			PackageTaskVo entity = new PackageTaskVo();
			String id = UUID.randomUUID().toString().replaceAll("-", "");
			entity.setId(id);
			entity.setAppId(mapParams.get("appId"));
			entity.setVersion(mapParams.get("version"));
			entity.setPlatform(mapParams.get("platform"));
			entity.setStatus(2);
			entity.setBuild(Integer.parseInt(mapParams.get("build")));
			entity.setRelease_note(mapParams.get("release_note"));
			entity.setCreateTime(date);
			entity.setFinishTime(date);

			// 进行打包处理
			AppMainVo app = appMainApplication.getEntity(entity.getAppId());
			PackageRequestVo packageRequestVo = new PackageRequestVo();
			packageRequestVo.setAppId(app.getIdentifier());
			packageRequestVo.setVersion(entity.getVersion());
			packageRequestVo.setVersionCode(entity.getBuild());
			packageRequestVo.setDesc(entity.getRelease_note());
			packageRequestVo.setPackageSeq(entity.getId());
			String appkey = applicationRegisterApplication
					.getAppKeyByAppId(entity.getAppId());
			if (appkey != null) {
				ApplicationRegisterVO arVo = applicationRegisterApplication
						.getByAppKey(appkey);
				if (arVo != null) {
					packageRequestVo.setUserId(arVo.getUsername());
				}
				packageRequestVo.setAppKey(appkey);
				if ("ios".equals(entity.getPlatform())) {
					int statusCode = this.requestIOSPackage(entity, app,
							request);
					if (statusCode == 200) {
						appPkgMetaInfoApplication.saveEntity(entity);// 保存打包记录
					}
				} else if ("android".equals(entity.getPlatform())) {
					packageRequestVo.setOS(Constants.ANDROID);
					log.info("[packageAdd]" + packageRequestVo.toString());
					appPackageApplication.pkgForCml(packageRequestVo);
					appPkgMetaInfoApplication.saveEntity(entity);// 保存打包记录
				}
				// 更新版本的状态
				AppVersionVo appversion = appVersionApplication.findByVersion(
						entity.getPlatform(), entity.getAppId(),
						entity.getVersion());
				if (appversion != null) {
					appversion.setStatus(2);
					appversion.setPlist(null);
					appversion.setBundle(null);
					appversion.setModified_time(new Date());
					appversion.setTask_id(entity.getId());
					appVersionApplication.updateEntity(appversion.getId(),
							appversion);
				}
				result.put("result", "success");
				result.put("task_id", entity.getId());
			} else {
				result.put("result", "error");
				result.put("appKey", appkey);
			}
		} catch (Exception e) {
			log.error("[packageAdd]", e);
			result.clear();
			result.put("result", "error");
		}
		log.info("[packageAdd]" + result.toString());
		return result;
	}

	/**
	 * 页面定时器，查询打包结果
	 * 
	 * @param versionIds
	 * @param bundles
	 * @param request
	 * 
	 * @return Map<String, Object>
	 */
	@ResponseBody
	@RequestMapping("/findBySeq")
	public Map<String, String> findBySeq(@RequestParam("task_id") String task_id) {
		Map<String, String> result = new HashMap<String, String>();
		try {

			PackageTaskVo taskVo = appPkgMetaInfoApplication.getEntity(task_id);
			if (taskVo != null) {
				if ("ios".equals(taskVo.getPlatform())) {
					result = this.findIOSPackStatus(taskVo);
				} else {
					result = this.findAndroidPackStatus(taskVo);
				}
			} else {
				log.info("[findBySeq]打包请求参数错误！");
				result.put("result", "success");
				result.put("status", "0");
			}

		} catch (Exception e) {
			log.error("[findBySeq]", e);
			e.printStackTrace();
			result.put("result", "error");
		}
		log.info("[findBySeq]" + result.toString());
		return result;
	}

	/**
	 * 通知打包结果
	 * 
	 * @param versionIds
	 * @param bundles
	 * @param request
	 * 
	 * @return Map<String, Object>
	 */
	@RequestMapping(value = "/callback/{task_id}", method = RequestMethod.GET)
	public ResponseEntity<String> callBackResult(
			@PathVariable("task_id") String task_id, HttpServletRequest request) {
		ResponseEntity<String> res = null;
		try {
			PackageTaskVo queryVo = this.queryPackageStatus(task_id);
			if (queryVo != null) {
				String sessionKey = request.getParameter("sessionKey");
				ContextThead.setThreadSessionKey(sessionKey);
				PackageTaskVo taskVo = appPkgMetaInfoApplication
						.getEntity(task_id);
				taskVo.setStatus(queryVo.getStatus());
				taskVo.setMsg(queryVo.getMsg());
				taskVo.setPackageUrl(queryVo.getPackageUrl());
				taskVo.setLogUrl(queryVo.getLogUrl());
				taskVo.setFinishTime(new Date());
				appPkgMetaInfoApplication.updateEntity(taskVo);// 更新数据库
				log.info("[通知打包结果]update success");
				res = new ResponseEntity<String>(HttpStatus.OK);
			} else {
				log.info("[callback]请求打包查询服务失败");
				res = new ResponseEntity<String>(
						HttpStatus.INTERNAL_SERVER_ERROR);
			}
		} catch (Exception e) {
			log.error("[通知打包结果]", e);
			e.printStackTrace();
			res = new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
		return res;
	}

	/**
	 * 生成plist文件
	 * 
	 * @param appId
	 * @param bundle
	 * @param request
	 * @return 返回文件的id
	 * @throws Exception
	 */
	private String getPlistTemplate(String appId, String bundle,
			HttpServletRequest request) throws Exception {
		InputStream is = AppPackageController.class
				.getResourceAsStream("/template.plist");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		try {
			while ((i = is.read()) != -1) {
				baos.write(i);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		String plistTemp = baos.toString();

		// 生成plist
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath();
		// 新增配置文件，可以支持使用http代理请求后台时候，生成plist文件下载地址
		String plistURL = rb.getString("plistURL");
		if (StringUtils.isNotEmpty(plistURL) && plistURL.startsWith("http")) {
			basePath = plistURL;
		}
		String url = basePath + "/mam/attachment/download/" + bundle;
		AppMainVo appMain = appMainApplication.getEntity(appId);
		if (plistTemp != null) {
			plistTemp = plistTemp.replaceAll("\\{bundle-identifier\\}",
					appMain.getIdentifier());
			plistTemp = plistTemp.replaceAll("\\{subtitle\\}",
					appMain.getApp_name());
			plistTemp = plistTemp.replaceAll("\\{title\\}",
					appMain.getApp_name());
			plistTemp = plistTemp.replaceAll("\\{url\\}", url);
		}

		String filename = appMain.getIdentifier() + ".plist";
		FileStorageFactory f = FileStorageFactory.getInstance();
		FileStorage fs = f.getFileStorage();
		String plistId = fs.saveFile(plistTemp.getBytes("utf-8"), null, null);

		AttachmentVO entity = new AttachmentVO();
		Date date = new Date();
		entity.setAvailable(1);
		entity.setContentType("application/octet-stream");
		entity.setCreatedAt(date);
		entity.setModifiedAt(date);
		entity.setUploadFilename(filename);
		entity.setSize(plistTemp.length());
		// 保存到云服务
		entity.setLocalFilename(plistId);
		AttachmentVO resultVo = attachmentApplication.saveEntity(entity);
		return resultVo.getId();
	}

	/**
	 * 调用打包服务接口，获取打包状态
	 * 
	 * @param task_id
	 * @return
	 * @throws Exception
	 */
	private PackageTaskVo queryPackageStatus(String task_id) {
		String buildUrl = rb.getString("packbuild.url");
		String url = buildUrl + "/build-progress/" + task_id;
		String task_status = "1";// 默认正在打包
		String msg = "";
		String logUrl = "";
		String packageUrl = "";
		String body = this.httpGet(url);
		if (body != null && !"".equals(body)) {
			PackageTaskVo taskVo = new PackageTaskVo();
			JSONObject json;
			try {
				json = new JSONObject(body.trim());
				task_status = json.getString("task_status");

				if (!json.isNull("packageUrl")) {
					packageUrl = json.getString("packageUrl");
				}
				if (!json.isNull("logUrl")) {
					logUrl = json.getString("logUrl");
				}
				msg = json.getString("msg");
				if ("3".equals(task_status)) {// 打包成功
					taskVo.setStatus(3);
				} else if ("4".equals(task_status)) {// 失败
					taskVo.setStatus(0);
				} else {
					taskVo.setStatus(2);
				}
			} catch (JSONException e) {
				log.error("[queryPackageStatus]", e);
			}
			taskVo.setPackageUrl(packageUrl);
			taskVo.setLogUrl(logUrl);
			taskVo.setMsg(msg);
			return taskVo;
		}
		return null;
	}

	/**
	 * 下载应用包
	 * 
	 * @param packageUrl
	 * @param identifier
	 * @param version
	 * @param platform
	 * @return
	 * @throws Exception
	 */
	private String downPackFile(String packageUrl, String identifier,
			String platform) {
		// 使用execute方法发送HTTP
		String bundle = this.httpDownFile(packageUrl);
		if (bundle != null) {
			// 读取云服务文件
			FileStorageFactory f = FileStorageFactory.getInstance();
			FileStorage fs = f.getFileStorage();
			FileInfo fileInfo = fs.statFile(bundle, null);
			// 保存上传文件信息
			AttachmentVO entityVo = new AttachmentVO();
			Date date = new Date();
			entityVo.setAvailable(1);
			entityVo.setContentType("application/octet-stream");
			entityVo.setCreatedAt(date);
			entityVo.setModifiedAt(date);
			if ("android".equals(platform)) {
				entityVo.setUploadFilename(identifier + ".apk");
			} else if ("ios".equals(platform)) {
				entityVo.setUploadFilename(identifier + ".ipa");
			}
			entityVo.setSize(fileInfo.getLength());
			entityVo.setLocalFilename(bundle);
			AttachmentVO resultVo = attachmentApplication.saveEntity(entityVo);
			return resultVo.getId();
		} else {
			log.info("[downPackFile]下载文件失败");
		}
		return null;
	}

	/**
	 * 封装http get方式请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private String httpGet(String url) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			HttpGet httpGet = new HttpGet(url);
			// 使用execute方法发送HTTP
			HttpResponse httpResponse = httpclient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			log.info("[httpGet]statusCode:" + statusCode);
			String body = EntityUtils.toString(httpResponse.getEntity(),
					"utf-8");
			log.info("[httpGet]body:" + body);
			if (statusCode == 200) {
				return body;
			}
		} catch (Exception e) {
			log.info("[httpGet]:", e);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return null;
	}

	/**
	 * 封装http get方式请求下载文件,返回文件id
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private String httpDownFile(String url) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		// 使用execute方法发送HTTP
		try {
			HttpResponse httpResponse = httpclient.execute(httpGet);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			log.info("[httpDownFile]statusCode:" + statusCode);
			String length = httpResponse.getFirstHeader("Content-Length")
					.getValue();
			log.info("[httpDownFile]Content-Length:" + length);
			if (statusCode == 200) {
				// 保存到云服务
				FileStorageFactory f = FileStorageFactory.getInstance();
				FileStorage fs = f.getFileStorage();
				String bundle = fs.saveFile(httpResponse.getEntity()
						.getContent());
				return bundle;
			}
		} catch (Exception e) {
			log.info("[httpDownFile]:", e);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return null;
	}

	/**
	 * 封装http Post方式请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws Exception
	 */
	private String httpPost(String url, Map<String, String> params) {
		DefaultHttpClient httpclient = new DefaultHttpClient();

		try {
			HttpPost post = new HttpPost(url);
			List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
			Set<String> keySet = params.keySet();
			for (String key : keySet) {
				nvps.add(new BasicNameValuePair(key, params.get(key)));
			}
			post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			// 使用execute方法发送HTTP
			HttpResponse httpResponse = httpclient.execute(post);
			int statusCode = httpResponse.getStatusLine().getStatusCode();
			log.info("[httpPost]statusCode:" + statusCode);
			String body = EntityUtils.toString(httpResponse.getEntity(),
					"utf-8");
			log.info("[httpPost]body:" + statusCode);
			if (statusCode == 200) {
				return body;
			}
		} catch (Exception e) {
			log.info("[httpPost]:", e);
		} finally {
			httpclient.getConnectionManager().shutdown();
		}
		return null;
	}

	/**
	 * 定时查询Ios打包
	 * 
	 * @param taskVo
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> findIOSPackStatus(PackageTaskVo taskVo)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		if (taskVo.getStatus() == 2) {// 打包状态
			long time = taskVo.getCreateTime().getTime();
			long ctime = new Date().getTime();
			long t = 10 * 60 * 1000;
			if (ctime - time > t) {// 超过打包时间10分钟,状态没有改变时候（即还没有收到打包回调的异步通知结果）,则去查询打包服务提供的查询接口
				PackageTaskVo queryVo = this.queryPackageStatus(taskVo.getId());
				if (queryVo != null) {
					taskVo.setStatus(queryVo.getStatus());
					taskVo.setMsg(queryVo.getMsg());
					taskVo.setPackageUrl(queryVo.getPackageUrl());
					taskVo.setLogUrl(queryVo.getLogUrl());
					taskVo.setFinishTime(new Date());
					appPkgMetaInfoApplication.updateEntity(taskVo);// 更新打包状态
				}
			}
		} else if (taskVo.getStatus() == 3) {// 打包成功
			AppMainVo app = appMainApplication.getEntity(taskVo.getAppId());
			// 下载安装包文件
			String bundle = this.downPackFile(taskVo.getPackageUrl(),
					app.getIdentifier(), taskVo.getPlatform());
			result.put("bundle", bundle);
			taskVo.setFinishTime(new Date());
			appPkgMetaInfoApplication.updateEntity(taskVo);// 更新打包状态
		}
		result.put("status", String.valueOf(taskVo.getStatus()));
		result.put("result", "success");
		return result;
	}

	/**
	 * 定时查询android打包
	 * 
	 * @param taskVo
	 * @return
	 * @throws Exception
	 */
	private Map<String, String> findAndroidPackStatus(PackageTaskVo taskVo)
			throws Exception {
		Map<String, String> result = new HashMap<String, String>();
		if (taskVo.getStatus() == 2) {// 打包状态
			long time = taskVo.getCreateTime().getTime();
			long ctime = new Date().getTime();
			long t = 10 * 60 * 1000;
			if (ctime - time > t) {// 超过打包时间10分钟,状态没有改变时候（即还没有收到打包回调的异步通知结果）,则默认打包失败
				taskVo.setStatus(0);
				taskVo.setMsg("没有收到异步通知结果，打包失败");
				taskVo.setPackageUrl(null);
				taskVo.setLogUrl(null);
				taskVo.setFinishTime(new Date());
				appPkgMetaInfoApplication.updateEntity(taskVo);// 更新打包状态
				result.put("bundle", "");
			}
		} else if (taskVo.getStatus() == 3) {// 打包成功
			result.put("bundle", taskVo.getPackageUrl());
		} else if (taskVo.getStatus() == 0) {
			result.put("bundle", "");
		}
		result.put("status", String.valueOf(taskVo.getStatus()));
		result.put("result", "success");
		return result;
	}

	/**
	 * 请求ios打包服务，进行打包
	 * 
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	private int requestIOSPackage(PackageTaskVo entity, AppMainVo app,
			HttpServletRequest request) throws Exception {

		String appkey = applicationRegisterApplication.getAppKeyByAppId(entity
				.getAppId());
		JSONObject jsonMsg = new JSONObject();
		jsonMsg.put("task_id", entity.getId());
		jsonMsg.put("identifier", app.getIdentifier());
		jsonMsg.put("appName", app.getApp_name());
		jsonMsg.put("appkey", appkey);
		jsonMsg.put("secret", app.getSecret());
		jsonMsg.put("build", entity.getBuild());
		jsonMsg.put("version", entity.getVersion());

		DefindVo defindPng = defindApplication.getEntityByAppId(
				entity.getPlatform(), entity.getVersion(), entity.getAppId());
		String url = rb.getString("callback.url");
		String downLoadURL = url + "/mam/attachment/download/";
		if (defindPng != null) {
			/* 设置logo (iphone) */
			String iconsLogo = defindPng.getIcons();
			JSONObject jsonIcons = new JSONObject();
			if (StringUtils.isNotEmpty(iconsLogo)) {
				JSONObject json = new JSONObject(iconsLogo);
				JSONObject phones = new JSONObject();
				if (!json.isNull("logo-xdpi")) {
					phones.put("max", downLoadURL + json.getString("logo-xdpi"));
				}
				if (!json.isNull("logo-hdpi")) {
					phones.put("mid", downLoadURL + json.getString("logo-hdpi"));
				}
				if (!json.isNull("logo-mdpi")) {
					phones.put("min", downLoadURL + json.getString("logo-mdpi"));
				}
				jsonIcons.put("phones", phones);
			}
			/* 设置logo (pad) */
			String iconsPad = defindPng.getIconsPad();
			if (StringUtils.isNotEmpty(iconsPad)) {
				JSONObject json = new JSONObject(iconsPad);
				JSONObject pad = new JSONObject();
				if (!json.isNull("logo-xdpi")) {
					pad.put("max", downLoadURL + json.getString("logo-xdpi"));
				}
				if (!json.isNull("logo-hdpi")) {
					pad.put("mid", downLoadURL + json.getString("logo-hdpi"));
				}
				if (!json.isNull("logo-hdpi")) {
					pad.put("min", downLoadURL + json.getString("logo-mdpi"));
				}
				if (!json.isNull("logo-mdpi")) {
					pad.put("default",
							downLoadURL + json.getString("logo-ldpi"));
				}
				jsonIcons.put("pad", pad);
			}

			jsonMsg.put("icons", jsonIcons);
			/* 设置 启动页 (iphone) */
			JSONObject jsonDefaultPages = new JSONObject();
			String defaultImgs = defindPng.getDefaultImgs();
			if (StringUtils.isNotEmpty(defaultImgs)) {
				JSONObject json = new JSONObject(defaultImgs);
				JSONObject phonesPages = new JSONObject();
				if (!json.isNull("default-xdpi")) {
					phonesPages.put("max",
							downLoadURL + json.getString("default-xdpi"));
				}
				if (!json.isNull("default-hdpi")) {
					phonesPages.put("mid",
							downLoadURL + json.getString("default-hdpi"));
				}
				if (!json.isNull("default-mdpi")) {
					phonesPages.put("min",
							downLoadURL + json.getString("default-mdpi"));
				}
				jsonDefaultPages.put("phones", phonesPages);
			}

			/* 设置 启动页 (pad) */
			String defaultImgsPad = defindPng.getDefaultImgsPad();
			if (StringUtils.isNotEmpty(defaultImgsPad)) {
				JSONObject json = new JSONObject(defaultImgsPad);
				JSONObject padPages = new JSONObject();
				if (!json.isNull("default-xdpi")) {
					padPages.put("max",
							downLoadURL + json.getString("default-xdpi"));
				}
				if (!json.isNull("default-hdpi")) {
					padPages.put("default",
							downLoadURL + json.getString("default-hdpi"));
				}
				jsonDefaultPages.put("pad", padPages);
			}

			jsonMsg.put("defaultPages", jsonDefaultPages);

		}

		// 获取证书信息
		AppSecretVo secret = appSecretApplication.findByAppId(
				entity.getAppId(), entity.getPlatform());
		if (secret != null) {
			jsonMsg.put("certificate", downLoadURL + secret.getCertid());
			jsonMsg.put("password", secret.getStorePass());
			jsonMsg.put("provision", downLoadURL + secret.getCertkey());
		}
		String sessionKey = (String) request.getSession().getAttribute(
				Constant.SESSION_KEY);
		String callBackUrl = url + "/mam/pkg/callback/" + entity.getId()
				+ "?sessionKey=" + sessionKey;
		jsonMsg.put("callback", callBackUrl);
		String buildUrl = rb.getString("packbuild.url");
		buildUrl = buildUrl + "/build-task/" + entity.getPlatform();
		log.info("[requestIOSPackage]url:" + buildUrl);
		Map<String, String> params = new HashMap<String, String>();
		params.put("msg", jsonMsg.toString());
		log.info("[requestIOSPackage]params:" + params.toString());
		String body = this.httpPost(buildUrl, params);
		if (body != null) {
			return 200;
		}
		return 400;
	}
}
